package com.donger.common.web.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * Http请求工具类
 *
 * @author xyx
 * @date 2019-01-11 20:17
 */
public class HttpContextUtil {

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        return Optional.ofNullable(request.getHeader("Origin")).orElse(StrUtil.EMPTY);
    }

    public static String getUserAgent() {
        HttpServletRequest request = getHttpServletRequest();
        return Optional.ofNullable(request.getHeader("user-agent")).orElse(StrUtil.EMPTY);
    }

    public static String getRemoteAddr() {
        HttpServletRequest request = getHttpServletRequest();
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return Optional.ofNullable(remoteAddr).orElse(request.getRemoteAddr());
    }

    public static String requestUrl() {
        return Optional.ofNullable(getHttpServletRequest().getRequestURI()).orElse(StrUtil.EMPTY);
    }

    public static String requestMethod() {
        return Optional.ofNullable(getHttpServletRequest().getMethod()).orElse(StrUtil.EMPTY);
    }
}
